package com.example.util;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间工具类
 *
 * @author royal
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";
    public static String YYYY_MM_DD_HH = "yyyy-MM-dd HH";
    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String HH = "HH";
    public static String HH_MM = "HH:mm";
    public static String HH_MM_SS = "HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getDateHH() {
        return dateTimeNow(HH);
    }

    public static String getDateHHMM() {
        return dateTimeNow(HH_MM);
    }

    /**
     * 获取当前日期, 默认格式为yyyyMMdd
     *
     * @return
     */
    public static String getDate2() {
        return dateTimeNow(YYYYMMDD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 获取当前月
     * @return
     */
    public static String getCurrentMonthTime(String date) {
        Calendar cal=Calendar.getInstance();
        cal.setTime(parseDate(date));
        return parseDateToStr(DateUtils.YYYY_MM, cal.getTime());
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param start
     * @param end
     * @return
     */
    public static int differentDays(Date start, Date end) {
        int days = (int) ((end.getTime() - start.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    /**
     * 拼接新的时间戳
     *
     * @param date
     * @param stayStartTime
     * @return
     */
    public static Date timeSpli(Date date, String stayStartTime) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //拼接开始
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        String str = year + "-" + month + "-" + day + " " + stayStartTime + ":00";
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
        Date startTimeDate = null;
        try {
            startTimeDate = sdf.parse(str.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return startTimeDate;
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoorStr(Date startDate, Date endDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "," + hour + "," + min;
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date startDate, Date endDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 计算两个时间差
     */
    public static Integer getDateMin(Date startDate, Date endDate) {
        long min = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();

        // 计算差多少小时
        Long totalMin = diff / min;
        if (diff % min != 0) {
            totalMin = totalMin + 1;
        }
        return totalMin.intValue();
    }

    public static Integer getDateMin1(Date startDate, Date endDate) {
        long min = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();

        // 计算差多少小时
        Long totalMin = diff / min;
        return totalMin.intValue();
    }

    /**
     * 计算两个时间差
     */
    public static Integer getDateHour(Date sDate, Date eDate) {
        long nh = 1000 * 60 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = eDate.getTime() - sDate.getTime();

        // 计算差多少小时
        Long totalHour = diff / nh;
        if (totalHour < 24){
            return totalHour.intValue();
        }else{
            if (diff % nh != 0) {
                totalHour = totalHour + 1;
            }
            return totalHour.intValue();
        }
    }

    public static Integer getCeilDateHour(Date sDate, Date eDate) {
        long nh = 1000 * 60 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = eDate.getTime() - sDate.getTime();

        // 计算差多少小时
        BigDecimal dif=new BigDecimal(diff);
        BigDecimal bn=new BigDecimal(nh);
        BigDecimal bn1=dif.divide(bn,2, BigDecimal.ROUND_HALF_UP);
//        Long totalHour = diff / nh;
        Long totalHour = bn1.setScale( 0, BigDecimal.ROUND_UP).longValue();
        if (totalHour < 24){
            return totalHour.intValue();
        }else{
            if (diff % nh != 0) {
                totalHour = totalHour + 1;
            }
            return totalHour.intValue();
        }
    }

    /**
     * 计算两个时间差
     */
    public static Double getDoubleDateHour(Date sDate, Date eDate) {
        // 获得两个时间的毫秒时间差异
        Double nh = Double.valueOf(1000 * 60 * 60);
        Double diff = Double.valueOf(eDate.getTime() - sDate.getTime());
        // 计算差多少小时
        Double totalHour = Math.ceil(diff / nh);
        return totalHour;
    }

    /**
     * 获取当前月第一天
     *
     * @return
     */
    public static Date getCurrentMouthFirstDayTime() {
        SimpleDateFormat format = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);

        //获取当前月第一天：
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 0);
        //设置为1号,当前日期既为本月第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();

    }

    /**
     * 获取指定分钟
     *
     * @return
     */
    public static Date getAfterMinute(Date date, int minute) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MINUTE, minute);
        return cal.getTime();
    }

    /**
     * 获取当前日期
     *
     * @return
     */
    public static String getCurrentDay() {
        Calendar cal = Calendar.getInstance();
        return parseDateToStr(DateUtils.YYYY_MM_DD, cal.getTime());
    }

    /**
     * 获取前一天时间
     *
     * @return
     */
    public static String getBeforeDayTime() {
        //获取当前一天

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        //Date d=cal.getTime();
        return parseDateToStr(DateUtils.YYYY_MM_DD, cal.getTime());
    }

    /**
     * 获取前一天时间
     *
     * @return
     */
    public static String getBeforeDayTime(Date date, int day) {
        //获取当前一天
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, -day);
        return parseDateToStr(DateUtils.YYYY_MM_DD, cal.getTime());
    }    /**
     * 获取前一天时间
     *
     * @return
     */
    public static String getBeforeDayTime(Date date, int day,String format) {
        //获取当前一天
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, -day);
        return parseDateToStr(format, cal.getTime());
    }

    /**
     * 获取后一天时间
     *
     * @return
     */
    public static String getAfterDayTime() {
        //获取后一天时间

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        //Date d=cal.getTime();
        return parseDateToStr(DateUtils.YYYY_MM_DD, cal.getTime());
    }

    /**
     * 获取推迟指定天数
     *
     * @return
     */
    public static Date getAfterDay(Date date, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }

    /**
     * 获取前一天时间
     *
     * @return
     */
    public static Date getBeforeDayDateTime() {
        //获取当前一天

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        //Date d=cal.getTime();
        return cal.getTime();
    }

    /**
     * 获取前一小时时间
     *
     * @return
     */
    public static Date getBeforeHourDateTime() {
        //获取当前一天

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR, -1);
        //Date d=cal.getTime();
        return cal.getTime();
    }

    /**
     * 获取前一小时时间
     *
     * @return
     */
    public static String getBeforeHourTime() {
        //获取前一小时
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR, -1);
        //Date d=cal.getTime();
        return parseDateToStr("yyyy-MM-dd HH", cal.getTime());
    }

    /**
     * 获取前一小时时间
     *
     * @return
     */
    public static String getBeforeHourDataTime() {
        //获取前一小时
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR, -1);
        //Date d=cal.getTime();
        return parseDateToStr("HH", cal.getTime());
    }

    /**
     * 获取前一小时时间
     *
     * @return
     */
    public static String getCurrentHourDataTime() {
        //获取前一小时
        Calendar cal = Calendar.getInstance();
        //Date d=cal.getTime();
        return parseDateToStr("yyyy-MM-dd HH", cal.getTime());
    }

    /**
     * 获取时分秒
     *
     * @return
     */
    public static String getTime(Date date, String format) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return parseDateToStr("HH:mm:ss", cal.getTime());
    }

    /**
     * 获取后一天时间
     *
     * @return
     */
    public static Date getAfterDayDateTime() {
        //获取当前一天

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        //Date d=cal.getTime();
        return cal.getTime();
    }

    /**
     * 获取前三天时间
     *
     * @return
     */
    public static Date getBeforeThreeDayTime() {
        //获取当前一天

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -3);
        //Date d=cal.getTime();
        return cal.getTime();
    }

    /**
     * 获取前七天时间
     *
     * @return
     */
    public static Date getBeforeSevenDayTime() {
        //获取当前一天

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -7);
        //Date d=cal.getTime();
        return cal.getTime();
    }

    /**
     * 获取前十五天时间
     *
     * @return
     */
    public static String getBeforeFifteenDayTime() {
        //获取前十五天

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -15);
        //Date d=cal.getTime();
        return parseDateToStr(DateUtils.YYYY_MM_DD, cal.getTime());
    }

    /**
     * 获取前十五天时间
     *
     * @return
     */
    public static Date getBeforeFifteenDayDateTime() {
        //获取前十五天

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -15);
        //Date d=cal.getTime();
        return cal.getTime();
    }

    /**
     * 获取当前月最后一天
     *
     * @return
     */
    public static Date getCurrentMouthLastDayTime() {
        SimpleDateFormat format = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);

        //获取当前月最后一天
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }

    /**
     * 根据年、月 获取当前月第一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        return cal.getTime();
    }

    /**
     * 根据年、月 获取当前月最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();

    }

    /**
     * 根据年、月 获取当前月最后一天
     *
     * @param date
     * @param monthNum
     * @return
     */
    public static Date getAfterSomeTimeDate(Date date, int monthNum) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, monthNum);
        return cal.getTime();

    }

    /**
     * 根据分钟获取小时分钟格式
     *
     * @param time
     * @return
     */
    public static String getHoursAndMin(int time) {
        int hours = (int) Math.floor(time / 60);
        int minute = time % 60;
        return hours + "小时" + minute + "分钟";

    }

    /**
     * 根据分钟获取小时分钟格式
     *
     * @param time
     * @return
     */
    public static String getHours(int time) {
        int hours = (int) Math.floor(time / 60);
        return hours + "";

    }

    /**
     * 根据分钟获取小时分钟格式
     *
     * @param time
     * @return
     */
    public static String getMin(int time) {
        int minute = time % 60;
        return minute + "";

    }

    /**
     * 根据当前时间获取一个月之后的时间
     *
     * @param someDay
     * @return
     */
    public static final Date getAfterDayTime(Integer someDay) {
        try {
            //当前时间
            Date dNow = new Date();
            //得到日历
            Calendar calendar = Calendar.getInstance();
            //把当前时间赋给日历
            calendar.setTime(dNow);
            //设置为后1月
            calendar.add(Calendar.DAY_OF_MONTH, someDay);
            //得到后1的时间
            return calendar.getTime();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据当前时间获取一个月之后的时间
     *
     * @return
     */
    public static final Date getAfterMouthTime() {
        try {
            //当前时间
            Date dNow = new Date();
            //得到日历
            Calendar calendar = Calendar.getInstance();
            //把当前时间赋给日历
            calendar.setTime(dNow);
            //设置为后1月
            calendar.add(Calendar.MONTH, 1);
            //得到后1个月后的时间
            return calendar.getTime();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取指定长度时间戳
     *
     * @param len
     * @return
     */
    public static long getTimeStamp(int len) {
        long timestamp = Timestamp.valueOf(LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0))).getTime();
        return len == 10 ? timestamp / 1000 : timestamp;
    }

    /**
     * 获取指定长度时间戳
     *
     * @param dateTime
     * @param len
     * @return
     */
    public static long getTimeStamp(Date dateTime, Integer len) {
        long timestamp = dateTime.getTime();
        return len == 10 ? timestamp / 1000 : timestamp;
    }

    /**
     * 计算天数、小时数、分钟数
     *
     * @param entryDate
     * @param exitDate
     * @return
     */
    public static Map<String, Object> calculateTimeDifference(Date entryDate, Date exitDate) {
        Map<String, Object> timeMap = new HashMap<String, Object>();
        long different = exitDate.getTime() - entryDate.getTime();

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long days = different / daysInMilli;
        different = different % daysInMilli;
        timeMap.put("days", new Long(days).intValue());
        long hours = different / hoursInMilli;
        different = different % hoursInMilli;
        timeMap.put("hours", new Long(hours).intValue());
        long minutes = different / minutesInMilli;
        timeMap.put("minutes", new Long(minutes).intValue());
        return timeMap;
    }

    /**
     * 计算停车时长
     *
     * @param entryDate
     * @param exitDate
     * @return
     */
    public static String parkTime(Date entryDate, Date exitDate) {
        Map<String, Object> timeMap = calculateTimeDifference(entryDate, exitDate);
        return timeMap.get("days") + "天" + timeMap.get("hours") + "小时" + timeMap.get("minutes") + "分钟";
    }

    /**
     * 获取两个时间分钟差
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static Integer getDateMin(String startDate, String endDate) {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date begin = null;
        Date end = null;
        try {
            begin = dfs.parse(startDate);
            end = dfs.parse(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long between = (end.getTime() - begin.getTime()) / 1000;
        long min = between / 60;
        return Integer.parseInt(min + "");
    }
    /**
     * 获取当天时间
     * @return
     */
    public static String getCurrentDayTime() {
        Calendar cal=Calendar.getInstance();
        return parseDateToStr(DateUtils.YYYY_MM_DD_HH, cal.getTime());
    }
    /**
     * 计算跨越天数
     * @param day1
     * @param day2
     * @return
     */
    public static long durDays(Date day1, Date day2) {
        if (day2.before(day1)) {
            return durDays(day2, day1) * -1;
        }
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(day1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(day2);
        long durDays = (day2.getTime()-day1.getTime())/(1000*3600*24);
        if (calendar2.get(Calendar.HOUR_OF_DAY) < calendar1.get(Calendar.HOUR_OF_DAY)
                || (calendar2.get(Calendar.HOUR_OF_DAY) == calendar1.get(Calendar.HOUR_OF_DAY)
                && calendar2.get(Calendar.MINUTE) < calendar1.get(Calendar.MINUTE))
                || (calendar2.get(Calendar.HOUR_OF_DAY) == calendar1.get(Calendar.HOUR_OF_DAY)
                && calendar2.get(Calendar.MINUTE) == calendar1.get(Calendar.MINUTE)
                && calendar2.get(Calendar.SECOND) < calendar1.get(Calendar.SECOND))) {
            durDays += 1;
        }
        return durDays;
    }
}

